from flask import request
from flask_restful import Resource, marshal_with, fields, reqparse

# restful 构建api
from models import User, db

# 返回格式
resource_fields = {
    'id': fields.Integer,
    'name': fields.String,
    'age': fields.String,
    'write_time': fields.String
}

class RestUser(Resource):
    # 格式化返回结果,envelope 数据显示名字
    @marshal_with(resource_fields, envelope="user")
    def get(self, id):
        return User.query.filter_by(id=id).first(), 200

    def post(self, name):
        # 解析参数
        parser = reqparse.RequestParser()
        # 添加参数,校验等,help: 校验不通过时展示自定义信息, location 可指定参数解析位置
        parser.add_argument('age', type=int, required=True,
                            help='年龄必须是整数,且不为空', location='form',
                            dest='age_alis')  # dest 使用别名存储参数,原来参数名key无法获取
        args = parser.parse_args()
        # age = request.form.get('age')
        user = User(name=name, age=args['age_alis'])
        db.session.add(user)
        db.session.commit()
        # 继承父类参数
        parser_copy = parser.copy()
        # 覆盖或者删除
        parser_copy.replace_argument('age', type=int, required=True)
        parser_copy.remove_argument('age')
        return "success"
    def delete(self, id):
        user = User.query.filter_by(id=id).first()
        db.session.add(user)
        return "ok"